package p2pcdnsim.network.example;

import p2pcdnsim.cdn.ObjectContent;
import p2pcdnsim.exception.PortAlreadyInUseException;
import p2pcdnsim.network.ApplicationProcess;
import p2pcdnsim.network.DatagramPacket;
import p2pcdnsim.network.DatagramSocket;
import desmoj.core.simulator.Model;

public class ExampleUDPServerProcess extends ApplicationProcess {

	public ExampleUDPServerProcess(Model owner, String name) {
		super(owner, name);
	}

	@Override
	protected void run() {
		DatagramSocket socket = null;
		try {
			socket = this.createDatagramSocket(80);
		} catch (PortAlreadyInUseException e) {
			throw new RuntimeException(e);
		}
		
		while(true) {
			System.out.println("["+this.currentTime()+"] Server: Waiting for a datagram...");
			DatagramPacket packet = socket.receive();
			ObjectContent content = (ObjectContent)packet.getMessage();
			
			System.out.println("["+this.currentTime()+"] Server: datagram received from "+packet.getSourceAddress()+": "+content);
			
			
			//Create a process to handle the incoming connection
			//ServerRoutine routine =  new ServerRoutine(this.getModel(),this.getName(),socket);
			//routine.activate(new SimTime(0.0));
			//System.out.println("["+this.currentTime()+"] Server: routine process created.");
		}
		
	
	}

//	private class ServerRoutine extends ApplicationProcess {
//
//		Socket socket;
//		
//		public ServerRoutine(Model owner, String name, Socket socket) {
//			super(owner, name);
//			this.socket = socket;
//		}
//		
//		@Override
//		protected void run() {
//			System.out.println("["+this.currentTime()+"] ServerRoutine: Accepted a connection: "+socket);
//	
//		}
//	}

}
